import { useUserStoreWithOut } from '@/store/modules/user';
import { isNumber } from 'lodash-es';

/**
 * @description 处理toFixed精度问题
 * @date 06/03/2023
 * @export
 * @param {number} num
 * @param {number} [decimals=2] 保留小数位
 */
export function formatToFixed(num: number, decimals: number = 2) {
  return (
    Math.round((parseFloat(num.toString()) + Number.EPSILON) * Math.pow(10, decimals)) /
    Math.pow(10, decimals)
  ).toFixed(decimals);
}


export const DEFAULT_SYMBOL = '￥'
export interface FormatMoneyOptions {
  money: number
  showFreeText?: boolean
  symbol?: string
  decimals?: number
  showSymbol?: boolean
}

/**
 * @description 处理金额
 * @date 21/06/2024
 * @export
 * @param {FormatMoneyOptions} options
 * @returns {*}  {string}
 */
export function formatMoney(options: FormatMoneyOptions): string {
  const { symbol = DEFAULT_SYMBOL, decimals = 2, showFreeText = false, showSymbol = true } = options
  const money = isNumber(options.money) ? options.money : 0;

  if (money <= 0 && showFreeText) {
    const { cocInfo } = useUserStoreWithOut()
    return cocInfo ? '会员免费' : '免费'
  }

  const m = formatToFixed(money, decimals)

  if (showSymbol) {
    return `${symbol}${m}`
  }

  return m
}